﻿using huqiang.Communication;
using huqiang.DataSet;
using System;
using System.Collections.Generic;

namespace huqiang.ProtoDataPro
{
    public class LogCmd
    {
        public const UInt16 UnityLog = 0;
        public const UInt16 ServiceLog = 1;
        public const UInt16 RedirectUnityLog = 127;
        public const UInt16 RedirectServiceLog = 128;
    }
    public class LogDataPro
    {
        public static void Handle(KcpUser link, int cmd, byte[] dat)
        {
            switch(cmd)
            {
                case LogCmd.UnityLog:
                    var log = ProtoSerializer.Deserialize<UnityLog>(dat);
                    if(log!=null)
                    {
                        OutLog.WriteLine(log.type);
                        OutLog.WriteLine(log.condition);
                        OutLog.WriteLine(log.stackTrace);
                    }
                    break;
                case LogCmd.ServiceLog:
                    var content = ProtoSerializer.Deserialize<StringContent>(dat);
                    if(content!=null)
                    {
                        OutLog.WriteLine(content.Text);
                    }
                    break;
                case LogCmd.RedirectUnityLog:
                    var address = ProtoSerializer.Deserialize<IPAddr>(dat);
                    if(address!=null)
                    {

                    }
                    break;
                case LogCmd.RedirectServiceLog:
                    if(Listener==null)
                    {
                        Listener = new List<KcpUser>();
                        Listener.Add(link);
                        OutLog.Log = RedirectServiceLog;
                    }
                    break;
            }
        }
        static List<KcpUser> Listener;
        static void RedirectServiceLog(string str)
        {
            if (Listener == null)
                return;
            StringContent content = new StringContent();
            content.Text = str;
            var dat = ProtoSerializer.Serialize(content);
            int c = Listener.Count - 1;
            for(;c>=0;c--)
            {
                if (Listener[c].Connected)
                {
                    Listener[c].Send(EnvelopeType.ProtoBuf,LogCmd.ServiceLog,dat,MsgType.Log);
                }
                else Listener.RemoveAt(c);
            }    
        }
    }
}
